<#
Multiple lines comments
#>
Set-PSDebug -Trace 1
#$ARTIFACT=(Get-ChildItem -path . -recurse -include *.jar).name
#$ARTIFACT=(Get-ChildItem -path target -recurse -include *.jar).name
#$ARTIFACT=(Get-ChildItem -path target -recurse -include *.jar)[0].name
#$ROOT=(get-item (get-location).path).Name
#$ROOT=(get-item -path (pwd)).name
#if ( -not (test-path 'log') ){ mkdir log }
$ROOT=(Get-Item -Path .\).BaseName

function chk{
   utf8 -From "top-camp" -To "top-camp-utf8"
   utf8 -From "top-camp-web" -To "top-camp-web-utf8"
}

<#
   utf8 "-From" "955wx" "-To" "955wx-utf8"
#>
function utf8{
   Param($From, $To)

   $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)

   Get-ChildItem -Exclude *.png,*.gif -Recurse -Force | where { !$_.PSisContainer } | where { !($_.Fullname -like "*.git*")} | foreach {

         #if($_.Extension -eq "png" || $_.Extension -eq "gif"){ continue }

         $path = $_.DirectoryName -replace "$From", "$To"
         $name = $_.Fullname -replace "$From", "$To"

         if ( !(Test-Path $path) ) {
            write-host $path
            New-Item -Path $path -ItemType directory
         }
         echo $_.Fullname

         $content = get-content $_.Fullname

         if ( $content -ne $null ) {

            [System.IO.File]::WriteAllLines($name, $content, $Utf8NoBomEncoding)
         } else {
            Write-Host "No content from: $_"   
         }
   }
}


function guess-version{
   write-host (get-content (get-childItem -Path .. -Include build.gradle -File -Recurse -ErrorAction SilentlyContinue)| where {$_ -match "\s+version\s+'(.+)'"})
   $matches[1]
}
#$VERSION=(guess-version)
#$ARTIFACT="${ROOT}-${VERSION}.jar"

function debug{
   java -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y -jar target\$ARTIFACT
}

function clean{
   $out = (ls . out -Recurse -Directory)
   foreach($i in $out){
      rmdir -Recurse -Force $i
   }
}

function login{
$passwd = convertto-securestring -AsPlainText -Force -String Powernet#2017
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "TEST003-PB\Administrator",$passwd
$session = new-pssession -computername 172.16.0.49 -credential $cred
enter-pssession $session
}

function rm-ext($fullPath){
   [io.path]::GetFileNameWithoutExtension($fullPath)
}

#dir d:\ | Where-Extension .txt,.log
Filter Where-Extension
{
   param
   (
       [String[]]
       $extension = ('.png', '.jpg', '.gif')
   )
   
   $_ |
   Where-Object {
       $extension -contains $_.Extension
   }
}

function mysql-info{
   @"
   use cbec_mysql;
   desc edi_client_queue;
   desc cbec_routing_info;
\q
"@ -replace "`r",""|mysql -v --user=devl --password=qwe456 --host=172.16.0.80
}
function mysql-exp{
   $db="cbec_mysql"
   $tbl="cbec_ent_goods"
   $ip="172.16.0.80"
   $user="devl"
   $pass="qwe456" 

   @"
   set names gbk;
   use $db;
   select * from $tbl limit 1;
\q
"@ -replace "`r",""|mysql --skip-column-names --host=$ip --user=$user --password=$pass >1.tsv
   cat 1.tsv
}
function upload{
   $files=@(ls *.sh)+(ls *.py)
   foreach($i in $files){
      vim -c "set ff=unix" -c "wq" $i
   }
   foreach($i in $files){
      scp $i 'root@172.16.0.59:/root/rabbitmq/'
      $fileName=($i).name
      @"
      chmod +x /root/rabbitmq/$fileName
      :
"@ -replace "`r",""|ssh 'root@172.16.0.59'
   }
}
function guess-pack{
   #get-content (get-childItem -Path . -Include build.gradle -File -Recurse -ErrorAction SilentlyContinue)|findstr /i "applicationId"
   write-host (get-content (get-childItem -Path . -Include build.gradle -File -Recurse -ErrorAction SilentlyContinue)| where {$_ -match '\s+applicationId\s+"(.+)"'})
   $matches[1]
}

function use-pem{
   <#
   chmod 400 'd:\Downloads\PB029.pem'
   icacls d:\Downloads\PB029.pem /grant junhuang:F
   icacls d:\Downloads\PB029.pem /inheritancelevel:r
   ssh -i 'd:/Downloads/PB029.pem' "root@49.234.211.204"
   #>
   ssh "root@49.234.211.204"
}

function publish{
   $ROOT=(Get-Item -Path .\).BaseName
   scp help.sh "root@${ip}:/root/$ROOT"
   @"
   cd /root/$ROOT
   chmod +x help.sh
   dos2unix help.sh
   :
"@ -replace "`r",""|ssh root@"$ip"
}

function publish{
   $ROOT=(Get-Item -Path .\).BaseName
   $ARTIFACT=(Get-ChildItem -path build/libs -recurse -include *.jar).name

   $list=@("build/libs/$ARTIFACT", "help.sh")
   foreach ($i in $list){
      scp $i "root@${ip}:/root/$ROOT"
   }
   @"
   cd /root/$ROOT
   chmod +x help.sh
   dos2unix help.sh
   :
"@ -replace "`r",""|ssh root@"$ip"
}

function nopass{
   $USER='powerbridge'
   $pass='Powernet'
   $ip='192.168.1.107'

   $USER_HOME='/Users/powerbridge'
   &d:\PuTTY\pscp.exe -pw $pass $env:USERPROFILE\.ssh\id_rsa.pub "${USER}@${ip}:$USER_HOME"
   @"
   cd $USER_HOME
   [ ! -f $USER_HOME/.ssh/authorized_keys ] && mkdir -p $USER_HOME/.ssh && touch $USER_HOME/.ssh/authorized_keys
   chattr -i $USER_HOME/.ssh/authorized_keys
   chmod +w $USER_HOME/.ssh/authorized_keys
   ls -l $USER_HOME/.ssh/authorized_keys
   cat id_rsa.pub >> $USER_HOME/.ssh/authorized_keys
   chattr +i $USER_HOME/.ssh/authorized_keys
   :
"@ -replace "`r",""|ssh $USER@"$ip"
}

function install-nssm{
   $file="nssm-2.24-101-g897c7ad.zip"
   $folder=[io.path]::GetFileNameWithoutExtension($file)
   #curl "https://nssm.cc/ci/$file" -O
   &$z7 x $file
   #rmdir -Path d:\nssm -Recurse -Force
   Rename-Item $folder nssm
   move -Force nssm d:\
}

function install-nginx{
   &$nssm install Nginx "d:\nginx-1.18.0\nginx.exe"
   &$nssm set Nginx AppDirectory "d:\nginx-1.18.0"
   &$nssm start Nginx
   &$nssm status Nginx
   curl.exe "http://localhost/"
}
function uninstall-nginx{
   &$nssm stop Nginx
   &$nssm remove Nginx
}
function nginx-status{
   &$nssm status Nginx
   &$FIREFOX "http://localhost:80"
   curl.exe "http://localhost/"
}
function kill-task($app){
   tasklist | findstr $app
   Taskkill /im $app /f
}

function install-PSfzf{
   #$env:PSModulePath
   $Modules="d:\powershell\7\Modules"
   #xcopy /s /y "d:\Downloads\PSFzf" $Modules
   Get-Module -ListAvailable|where {$_ -Match "PSFzf"}
   Import-module -name "PSFzf"
   Set-PsFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
}

function install-iis{
   Set-ExecutionPolicy Bypass -Scope Process

   $PSDefaultParameterValues['Import-Module:Verbose'] = $false
   Import-Module WebAdministration
   $PSDefaultParameterValues['*:Verbose'] = $true

   #Get-WindowsOptionalFeature -Online | where FeatureName -like 'IIS-*'
   Get-WindowsOptionalFeature -Online | where FeatureName -like 'Web-Scripting-Tools'

   #$IISFeatures = @("Web-WebServer","Web-Common-Http","Web-Default-Doc","Web-Dir-Browsing","Web-Http-Errors","Web-Static-Content","Web-Http-Redirect","Web-Health","Web-Http-Logging","Web-Custom-Logging","Web-Log-Libraries","Web-ODBC-Logging","Web-Request-Monitor","Web-Http-Tracing","Web-Performance","Web-Stat-Compression","Web-Security","Web-Filtering","Web-Basic-Auth","Web-Client-Auth","Web-Digest-Auth","Web-Cert-Auth","Web-IP-Security","Web-Windows-Auth","Web-App-Dev","Web-Net-Ext","Web-Net-Ext45","Web-Asp-Net","Web-Asp-Net45","Web-ISAPI-Ext","Web-ISAPI-Filter","Web-Mgmt-Tools","Web-Mgmt-Console")
   #Install-WindowsFeature -Name $IISFeatures

   $IISfeatures = @("IIS-WebServerRole", "IIS-WebServer", "IIS-CommonHttpFeatures", "IIS-HttpErrors", "IIS-HttpRedirect", "IIS-ApplicationDevelopment", "NetFx4Extended-ASPNET45", "IIS-NetFxExtensibility45", "IIS-HealthAndDiagnostics", "IIS-HttpLogging", "IIS-LoggingLibraries", "IIS-RequestMonitor", "IIS-HttpTracing", "IIS-Security", "IIS-RequestFiltering", "IIS-Performance", "IIS-WebServerManagementTools", "IIS-IIS6ManagementCompatibility", "IIS-Metabase", "IIS-ManagementConsole", "IIS-BasicAuthentication", "IIS-WindowsAuthentication", "IIS-StaticContent", "IIS-DefaultDocument", "IIS-WebSockets", "IIS-ApplicationInit", "IIS-ISAPIExtensions", "IIS-ISAPIFilter", "IIS-HttpCompressionStatic", "IIS-ASPNET45")

   Foreach ($f in $IISFeatures){
      enable-windowsOptionalFeature -Online -FeatureName $f
      #Disable-WindowsOptionalFeature
   }

   "xxx"|out-file -filePath C:\inetpub\wwwroot\xxx.html
   curl.exe http://localhost/xxx.html

}

function add-webpool{

   #Remove-Website -Name "Default Web Site"
   #$defaultAppPools = @(".NET v2.0",".NET v2.0 Classic",".NET v4.5",".NET v4.5 Classic","Classic .NET AppPool","DefaultAppPool")
   #Foreach ($defaultAppPool in $defaultAppPools){ IF (Test-path "IIS:\AppPools\$defaultAppPool"){Remove-WebAppPool -name $DefaultAppPool} }

   #$HARDDRIVE=(get-psdrive)[3].root
   $HARDDRIVE=(Get-PSDrive | Select-Object -ExpandProperty 'Root' | Select-String -Pattern '^[a-z]:\\$')[1]
   $NewFolders = "inetpub", "inetpub\html"
   $NewFolders | ForEach-Object { if(!(Test-Path -Path $HARDDRIVE\$_)){ New-Item $HARDDRIVE\$_ -type directory } }

   #Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -name logfile.directory -value $HARDDRIVE\inetpub

   Remove-WebAppPool -name "NewWebSiteAppPool" -force
   New-WebAppPool -name "NewWebSiteAppPool" -force

   $PSDefaultParameterValues["Disabled"]=$true
   $appPool = Get-Item -name "NewWebSiteAppPool" 
   $appPool.processModel.identityType = "NetworkService"
   $appPool.enable32BitAppOnWin64 = 1
   $appPool | Set-Item

   if(!(Test-Path -Path $HARDDRIVE\"inetpub\html")){md $HARDDRIVE\"inetpub\html"}

   # All on one line
   new-WebSite -name "NewWebSite" -PhysicalPath $HARDDRIVE\"inetpub\html" -HostHeader "xxx.com" -ApplicationPool "NewWebSiteAppPool" -force

   # PowerShell ISE
   #curl.exe http://localhost/html
}

function logical-disk{
   (Get-PSDrive | Select-Object -ExpandProperty 'Root' | Select-String -Pattern '^[a-z]:\\$')[1].Line.Trim()
}
function publish{
   $ROOT=(Get-Item -Path .\).BaseName
   $ARTIFACT=(Get-ChildItem -path build/libs -recurse -include *.jar).name

   $list=@("build/libs/$ARTIFACT", "help.sh")
   foreach ($i in $list){
      scp $i "root@${ip}:/root/$ROOT"
   }
   @"
   cd /root/$ROOT
   chmod +x help.sh
   dos2unix help.sh
   :
"@ -replace "`r",""|ssh root@"$ip"
}

function debug{
   java `
   -Denv=local `
   -Xms128m `
   -Xmx256m `
   -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y `
   -jar target\$ARTIFACT
}

function boot{
   $ARTIFACT=Get-ChildItem -path target -Recurse -Depth 1 -include *jar-with-dependencies.jar
   #$ARTIFACT=Get-ChildItem -path target/scala-* -Recurse -Depth 1 -include *.jar
   if($ARTIFACT){
      #java "-Djava.ext.dirs=.\lib:$env:JAVA_HOME\lib:$env:JAVA_HOME" -cp $ARTIFACT tt
      java -jar $ARTIFACT
   }
}

function build{
   mvn clean package
   #mvn clean scala:compile compile package
}

function reboot{
   &build
   &boot
}

if ($args.Length -gt 0){ &$args[0] $args[1..$args.Length] }
